package com.vimi8.chick.plugins.widgets.dialogs

import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.vimi8.chick.plugins.R

abstract class BaseDialogFragment : DialogFragment() {

    protected abstract fun getResourceId(): Int

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(getResourceId(), container)
    }


    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        setStyle(DialogFragment.STYLE_NORMAL, R.style.common_dialog_transparent)
        return super.onCreateDialog(savedInstanceState)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initData(savedInstanceState)
        initView(view)
    }

    protected open fun setAnimations(): Int {
        return 0
    }

    private fun getAnimations(): Int {
        var anim = setAnimations()
        if (anim == 0) {
            anim = R.style.common_dialog_anim_bt
        }
        return anim
    }

    /**
     * 初始化数据
     */
    protected open fun initData(savedInstanceState: Bundle?) {}

    /**
     * 初始化 View
     */
    protected open fun initView(view: View) {}

    override fun onDismiss(dialog: DialogInterface?) {
        super.onDismiss(dialog)
    }

    override fun onResume() {
        super.onResume()
        dialog.window.attributes.windowAnimations = getAnimations()
        dialog.window.setDimAmount(0.5f)
        val dialogWindow = dialog.window
        val lp = dialogWindow!!.attributes
        dialogWindow.setGravity(Gravity.CENTER)
        dialogWindow.attributes = lp
    }

    /**
     * 调整dialog的size和位置
     *
     * @param x
     * @param y
     * @param gravity
     */
    protected fun adjustSizeGravity(x: Int, y: Int, gravity: Int) {
        val dialogWindow = dialog.window
        val lp = dialogWindow!!.attributes
        lp.width = if (x == -1) lp.width else x
        lp.height = if (y == -1) lp.height else y
        dialogWindow.setGravity(gravity)
        dialogWindow.attributes = lp
    }

}
